<template>
	<scroll-view
		class="pictrues"
		:scroll-y="true"
		scroll-with-animation="true"
		@scrolltolower="onReachBottom"
	>
	  <view class="pictrues-1">
	    <view class="pictrues-2">
	      <view class="pictrues-3">
	        <view
	          v-for="(pics, index) of pictureList"
	          :key="index"
	          :style="{ 'margin-left': !index ? '' : '10rpx' }"
	          class="pic-row"
	        >
	          <view
	            v-for="(pic, ind) of pics"
	            :key="ind"
	            class="pic-item"
	            :style="{'padding-top': 1 / (pic.wh_radio - 0) * 100 + '%'}"
							@click="preview(pic)"
	          >
	            <span class="cover-div"></span>
	            <image
	              mode="aspectFit"
	              class="pic-item-content"
	              :src="pic?.url || '#'"
	            />
	          </view>
	        </view>
	      </view>
	    </view>
	  </view>
		<!-- 图片预览 -->
		<qPreviewImage
			ref="previewImage"
			:urls="previewPicture"
			@onLongpress="onLongpress"
			@open="open"
			@close="close"
		></qPreviewImage>
	</scroll-view>
	<!-- 空白页面 -->
	<view v-if="!userInfo?.uid" class="no-login">
		<view>
			暂未登录，请先
			<navigator style="margin: 0 4px;color: #2b69b3;display: inline-block" url="/pages/login/index">
				登录
			</navigator>
		</view>
	</view>
	<view v-if="userInfo?.uid && !pictureList?.length">
		<view>暂无图片数据，请移步</view>
		<view>{{ url }}</view>
		<view @click="onCopy">（复制）</view>
		<view>维护个人图片数据</view>
	</view>
</template>

<script lang="ts" setup>
import { debounce } from "lodash";
import { nextTick, ref, Ref } from "vue";
import { appletUserInfo, searchPersonPicture } from "../../service/index";
import { createToastComp } from "../../utils/comp";
import { qPreviewImage } from "@/uni_modules/q-previewImage/components/q-previewImage/q-previewImage.vue";

const pageNumber = ref(1); // 图片当前页
const pageSize = ref(10); // 页大小
const pageCount = ref(1); // 总页数
const total = ref(1); // 总大小
const pictureList = ref([]); // 图片列表

const previewImage = ref(null);
const previewPicture = ref([]); // 预览图片列表

// 滚动到最底部时
const onReachBottom = debounce(() => {
	if (pageNumber.value < pageCount.value) {
		pageNumber.value++;
		_searchPicture();
	} else {
		createToastComp({ title: "到底了", mask: false }, "success");
	}
}, 300);

/**
 * 分页查询所有图片
 */
const _searchPicture = async (reset = false) => {	
	if (reset) {
		total.value = 0;
		pageCount.value = 0;
		pageNumber.value = 1;
	}
	const params: any = {
		pageNumber: pageNumber.value,
		pageSize: pageSize.value,
		include_url: userInfo.value?.pic_url,
	};
	const res: any = await searchPersonPicture(params);
	if (res.status === "success") {
		const dataList = res?.data?.list || [];
		// 处理图片格式
		total.value = res?.data?.total || 0,
		pageCount.value = Math.ceil((res?.data?.total || 0) / res?.data?.pageSize)
		let firstColumn = []; // 第一列
		let secondColumn = []; // 第二列
		let previewColumn = []; // 预览列表
		if (pageNumber.value > 1) {
			firstColumn = pictureList.value[0]; // 第一列
			secondColumn = pictureList.value[1]; // 第二列			
			previewColumn = previewPicture.value;
		}
		dataList.forEach((item: any, index: number) => {
			if ((index + 1) % 2 === 1) {
				firstColumn.push(item);
			} else if ((index + 1) % 2 === 0) {
				secondColumn.push(item);
			}
		});
		pictureList.value = [firstColumn, secondColumn];
		previewColumn.push(...dataList.map((i: any) => i.url));
		previewPicture.value = previewColumn;
	} else {
		createToastComp({ title: res.msg || "错误" }, "error");
	}
};

const userInfo: Ref<null | Object> = ref(null); // 用户ID
// Vue 3的Composition API和uni-app生命周期一起使用的方式
const page = getCurrentPages()?.find(i => i.route === "pages/my-picture/index");
page && (page.onShow = async function() {
	const res: any = await appletUserInfo(uni.getStorageSync('token'));
	if (res.status !== "success") return;
	if (res.data?.length == 1) {
		userInfo.value = res.data?.[0] || null;
		uni.setStorageSync("userInfo", userInfo.value || {});
	}
	if (userInfo.value) {
		_searchPicture();
	}
});

const preview = (item: any) => {
	if (!item.url || item.url === "#") return;
	// #ifdef MP-WEIXIN
	nextTick(() => {
		previewImage.value.open(item.url); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
	});
	// #endif
	// #ifndef MP-WEIXIN
	previewImage.value.open(item.url); // 传入当前选中的图片地址
	// #endif
};

const onLongpress = (url: any) => {
	// TODO：暂未实现
	// uni.showActionSheet({
	// 	itemList: ['转发给朋友', '保存到手机'],
	// 	success: function (res) {
	// 		console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
	// 	},
	// 	fail: function (res) {
	// 		console.log(res.errMsg);
	// 	}
	// });
}

/* open和close方法一般用不到，但是在一些特殊场景会用到，
* 比如预览图片时你需要覆盖 NavigationBar和 TabBar，
* 或者在app中需要预览图片时覆盖住原生组件，比如video或者map等，
* 你可以根据open和close去做一些操作，例如隐藏导航栏或者隐藏一些原生组件等
*/
const open = () => { //监听组件显示 （隐藏TabBar和NavigationBar，隐藏video原生组件）
	// uni.hideTabBar()
	// uni.setNavigationBarColor({
	//  frontColor: '#000000', // 设置前景色为黑色
	//  backgroundColor: '#000000', // 设置背景色为黑色
	// })
	// data.videoShow = false 
}

const close = () => { //监听组件隐藏 （显示userInfo和NavigationBar，显示video原生组件）
	// uni.showTabBar()
	// uni.setNavigationBarColor({
	//  frontColor: '#ffffff', // 设置前景色为白色
	//  backgroundColor: '#000000', // 设置背景色为黑色
	// })
	// data.videoShow = true
}

// 复制到粘贴板
const url = ref("http://www.dangxiajing.cn:8080/");
const onCopy = () => {
	uni.setClipboardData({
		data: url.value,
		success: function () {
			createToastComp({ title: "复制成功" }, "success")
		}
	})
};
</script>

<style lang="less" scoped>
.pictrues {
	height: 100vh;
	overflow: auto;
	.pictrues-1 {
		color: #656f79;
		width: 100%;
		display: inline-block;
		overflow: auto;
		padding: 10rpx;
		.pictrues-2 {
			margin-bottom: 20rpx;
			position: relative;
		}
	}
}

.pictrues-3 {
	display: flex;
	align-items: flex-start;
	overflow: hidden;
	width: 100%;
}
.pic-row {
	flex: 1;
}
.pic-item {
	margin-bottom: 10rpx;
	position: relative;
	cursor: pointer;
}
.pic-item .cover-div {
	display: block;
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	filter: opacity(0.3);
	background-color: #0f0186;
	border-radius: 14rpx;
}
.pic-item-content {
	height: 100%;
	width: 100%;
	overflow: hidden;
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	border-radius: 14rpx;
}
.pic-item-content > img {
	width: 100%;
	height: 100%;
	max-width: 100%;
	max-height: 100%;
}
.pic-item-content > img .overlay {
	opacity: 0;
	transition: all 0.25s;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	cursor: pointer;
	pointer-events: none;
}
.pic-item-content > img .overlay-controls {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	padding: 16rpx;
	background: linear-gradient(
		180deg,
		rgba(25, 27, 38, 0.56),
		rgba(25, 27, 38, 0)
	);
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 8rpx;
	cursor: pointer;
	pointer-events: auto;
}
.left-icon {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32rpx;
	height: 32rpx;
	border-radius: 8rpx;
	border: 1rpx solid hsla(0, 0%, 100%, 0.4);
	background: hsla(0, 0%, 100%, 0.1);
	color: #fff;
	text-decoration: none;
	cursor: pointer;
	font-size: 20rpx;
}
.pic-item-content > img .overlay-bottom {
	position: absolute;
	display: flex;
	gap: 8rpx;
	left: 0;
	bottom: 0;
	width: 100%;
	padding: 16rpx;
	background: linear-gradient(
		180deg,
		rgba(25, 27, 38, 0),
		rgba(25, 27, 38, 0.56)
	);
	cursor: pointer;
	pointer-events: auto;
	color: hsla(0, 0%, 100%, 0.8);
}

.no-login {
	position: absolute;
	top: 0%;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 44rpx;
}
</style>